package com.example.pingze.service;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.example.pingze.entity.ID;
import com.example.pingze.entity.Sentence;
import com.example.pingze.entity.Sentence1;
import com.example.pingze.repository.SentenceFileRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Service
public class SentenceFileService {
    @Autowired
    private SentenceFileRepository repository;

    public List<Sentence> fromJson() {
        List<Sentence> sentenceList = new ArrayList<>();
        String json = "C:\\Users\\asus\\Desktop\\chinese-gushiwen\\sentence\\22.json";
        File jsonFile = new File(json);
        String jsonData = getJsonStr(jsonFile);
        JSONArray jsonArray = JSONUtil.parseArray(jsonData);
        List<Sentence1> sentences = JSONUtil.toList(jsonArray,Sentence1.class);
        for(Sentence1 list : sentences){
            Sentence sentence = getSentencesList(list);
            sentenceList.add(sentence);
        }
        return sentenceList;
    }

    private Sentence getSentencesList(Sentence1 list) {
        Sentence sentence = new Sentence();
        ID id = list.get_id();
        String oid = id.get$oid();
        String Name = list.getName();
        String from = list.getFrom();
        sentence.setId(oid);
        sentence.setSentence(Name);
        sentence.setSentenceFrom(from);
        return sentence;
    }

    public String getJsonStr(File file){
        String jsonStr = "";
        try {
            FileReader fileReader = new FileReader(file);
            Reader reader = new InputStreamReader(new FileInputStream(file));
            int ch = 0;
            StringBuffer buffer = new StringBuffer();
            while (((ch = reader.read()) != -1)) {
                buffer.append((char)ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = buffer.toString();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
        return jsonStr;
    }
    public void insertSentence(List<Sentence> list) {
        for (Sentence sentence : list) {
            repository.save(sentence);
        }
    }
}
